package com.wave.system.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.TimeUnit;


@Slf4j
public class QRScannerUtil {

    /**
     * 获取二维码数据
     *
     * @param ip：扫码器的ip地址
     * @return 返回二维码数据
     */
    public static String getQrCodePre(String ip) {
        Socket socket = null;
        try {
            socket = new Socket(ip, 2112);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("start".getBytes());
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int read = inputStream.read(bytes);
            String ret = new String(bytes, 0, read);
            log.info("产品二维码数据snCode:{}", ret);
            if (StringUtils.isNotBlank(ret) && !"NoRead".equals(ret)) {
                return ret;
            }
        } catch (Exception e) {
            log.info("扫码器读取二维码数据报错,ip地址为：{}，报错信息为：{}", ip, e.getMessage());
            return null;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    log.info("关闭扫码器socket：{}失败，报错信息为：{}", ip, e.getMessage());
                }
            }
        }
        return null;
    }

    public static String getQrCode(String ip) throws InterruptedException {
        String result = "";
        int i = 0;
        while (i < 5) {
            i++;
            result = getQrCodePre(ip);
            if (StringUtils.isNotBlank(result)) {
                return result;
            }
            TimeUnit.MILLISECONDS.sleep(100);
        }
        return null;
    }

    public static void main(String[] args) throws InterruptedException {
        getQrCode("192.168.150.211");
    }

}
